﻿using Model;
using Newtonsoft.Json.Linq;
using PublicMethod;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web;
using System.Web.Mvc;

namespace OrderingOnlineWeChat.Controllers
{
    public class HomeController : Controller
    {
        DCXTService.Service1Client DCXT2 = new DCXTService.Service1Client();
        ZHHQService.Service1Client ZHHQ1 = new ZHHQService.Service1Client();

        /// <summary>
        /// czx:增加登录等待页面.20160727
        /// </summary>
        /// <returns></returns>
        public ActionResult LoginWait()
        {
            //【2】获取参数： 
            string url = HttpContext.Request.Url.Query;
            //【1】获取完整url （协议名+域名+虚拟目录名+文件名+参数） 
            //string url1 = Request.Url.ToString();
            //Log.Debug("url1", url);
            string canshu = url.Substring(url.LastIndexOf("=") + 1);

            string[] cs = canshu.Split('&');
            string acctoken = cs[1];
            Session["acctoken"] = acctoken;
            //Log.Debug("acctoken", acctoken);
            ViewBag.YZM = cs[0];

            return View();

        }

        #region View
        /// <summary>
        /// 首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            #region 测试用
            //string openid = "oqxe8uLl88sAjplcKGh8pbm8lLmA";//用于网页测试       
            //Session[SessionStorage.OpenID] = openid;
            //string a = Session[SessionStorage.OpenID].ToString();
            //string res = DCXT2.DCUserLogin_WeiXin(openid, GetYZM._YZM, 1);
            //JObject job = JObject.Parse(res);
            //string bs = job["BS"].ToString();
            //if (bs == "1")//表示该微信号已经绑定过帐号
            //{
            //    Model.View_User dataresult = new View_User();
            //    IList<JToken> jieguo = job["rows"].Children().ToList();//将json数据转成多条
            //    dataresult = obser<Model.View_User>.DataContractJsonDeserialize(job["rows"].ToString());//将json格式转为实体类
            //    Session[SessionStorage.UserLogin] = dataresult;//将实体类保存至Session
            //    Session.Timeout = 60;//设置session的有效时间为60分钟
            //    return View();
            //}
            //else//标识该微信号未绑定帐号，要求微信用户绑定帐号
            //{
            //    Response.Redirect("Home/Binding");
            //    return View();
            //}
            #endregion

            #region 这是一个微信的请求（或者是一个空请求） 
            Log.Debug("微信登录", "进入主页");
            string openid = Request.QueryString["OpenIDToken"];

            if (openid == "" || openid == null)
            {
                Log.Debug("", "openid为空");
                string authaddr = ConfigurationManager.AppSettings.Get("authaddr");
                Log.Debug("授权地址", authaddr);
                string Webaddr = ConfigurationManager.AppSettings.Get("WebAddr");
                Log.Debug("网站本身地址", Webaddr);
                //是一个空的请求
                Log.Debug("跳转地址", authaddr + "?reurl=" + Webaddr);
                return Redirect(authaddr + "?reurl=" + Webaddr);
            }
            else
            {
                Log.Debug("获取到Openid", openid);
                Session[SessionStorage.OpenID] = openid;
                string res = DCXT2.DCUserLogin_WeiXin(openid, GetYZM._YZM, 1);
                Log.Debug("微信登录", openid + " 接口返回：" + res);
                JObject job = JObject.Parse(res);
                string bs = job["BS"].ToString();
                if (bs == "1")//表示该微信号已经绑定过帐号
                {
                    Model.View_User dataresult = new View_User();
                    IList<JToken> jieguo = job["rows"].Children().ToList();//将json数据转成多条
                    dataresult = obser<Model.View_User>.DataContractJsonDeserialize(job["rows"].ToString());//将json格式转为实体类
                    Session[SessionStorage.UserLogin] = dataresult;//将实体类保存至Session
                    Session.Timeout = 60;//设置session的有效时间为60分钟
                    return View();
                }
                else//标识该微信号未绑定帐号，要求微信用户绑定帐号
                {
                    Response.Redirect("Home/Binding");
                    return View();
                }
            }
            #endregion
        }
        /// <summary>
        /// 异常界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Unusual()
        {
            return View();
        }
        /// <summary>
        /// 关注二维码界面
        /// </summary>
        /// <returns></returns>
        public ActionResult TwoDBarcode()
        {
            return View();
        }
        /// <summary>
        /// 绑定帐号界面
        /// </summary>
        /// <returns></returns>
        public ActionResult Binding()
        {
            return View();
        }

        /// <summary>
        /// 商品搜索界面
        /// </summary>
        /// <returns></returns>
        public ActionResult SeachProductos()
        {
            return View();
        }
        #endregion

        #region 打开首页判断
        /// <summary>
        /// 打开首页判断----当未关注公众号的时候显示二维码界面，当未绑定帐号是显示绑定帐号界面，当成功时显示首页
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckIn()
        {
            #region 首先判断访问者是否具备以下入参，如果没有值，这是一个外链，显示二维码要求用户关注公众号
            ////首先判断访问者是否具备以下入参，如果没有值，这是一个外链，显示二维码要求用户关注公众号
            //string code = Request.QueryString["code"];
            //string state = Request.QueryString["state"];
            ////string code = "1";
            ////string state = "nnzbzh";

            ////state的值是预先在微信后台设置好的，防止其他系统误传参到本系统中
            //if (code == "" || code == null || state != "nnzbzh")
            //{
            //    Response.Redirect("Home/TwoDBarcode");
            //    return View();
            //}
            //else
            //{
            //    #region 发送http请求获取用户ID
            //    //能正常获取到入参，提交入参给公众号，申请用户的唯一ID
            //    //创建一个HTTP get请求
            //    string ph = "https://api.weixin.qq.com/sns/oauth2/access_token?";
            //    //appid和secret是微信公众号的认证信息，已经设置好
            //    string aaaaa = "appid=wx2e28a4845155deb6&secret=0aa8046f4734535ed30632dc599df6e2&code=" + code + "&grant_type=authorization_code";
            //    string result = "";
            //    HttpWebRequest request = WebRequest.Create(ph + aaaaa) as HttpWebRequest;//as HttpWebRequest;
            //    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            //    {
            //        StreamReader reader = new StreamReader(response.GetResponseStream());
            //        result = reader.ReadToEnd();
            //    }
            //    #endregion

            //    #region 接收返回信息并转换处理
            //    //定义返回成功和返回失败的类
            //    ReOkData rok = new ReOkData();
            //    ReErrorData rError = new ReErrorData();
            //    //定义一个标识告诉程序成功与否
            //    bool IsOk = false;
            //    //由于返回成功和错误的格式不一样，所以在转换过程可能不匹配导致异常，
            //    //获得异常后使用错误的格式再解析一次。
            //    try
            //    {
            //        rok = JsonHepler.JsonDeserializeBySingleData<ReOkData>(result);
            //        IsOk = true;
            //    }
            //    catch
            //    {
            //        try
            //        {
            //            rError = JsonHepler.JsonDeserializeBySingleData<ReErrorData>(result);
            //            IsOk = false;
            //        }
            //        catch { };
            //    }
            //    #endregion

            //    #region 根据返回值提示用户，
            //    //这里加入相关逻辑.........
            //    if (IsOk)
            //    {
            //        //rok.openid = "oqxe8uL188sAjp1cKGh8pbm81LmA";//用于网页测试
            //        Session[SessionStorage.OpenID] = rok.openid;
            //        //return Content("欢迎回来，您的凭证：" + rok.openid + "   您的来源合法凭证：" + state);
            //        string res = ZHHQ1.UserLogin_WeiXin(rok.openid, GetYZM._YZM, 1);
            //        JObject job = JObject.Parse(res);
            //        string bs = job["BS"].ToString();
            //        if (bs == "1")//表示该微信号已经绑定过帐号
            //        {
            //            Model.View_User dataresult = new View_User();
            //            IList<JToken> jieguo = job["rows"].Children().ToList();//将json数据转成多条
            //            dataresult = obser<Model.View_User>.DataContractJsonDeserialize(job["rows"].ToString());//将json格式转为实体类
            //            Session[SessionStorage.UserLogin] = dataresult;//将实体类保存至Session
            //            Session.Timeout = 60;//设置session的有效时间为60分钟
            //            Response.Redirect("Home/Index");
            //            return View();
            //        }
            //        else//标识该微信号未绑定帐号，要求微信用户绑定帐号
            //        {
            //            Response.Redirect("Home/Binding");
            //            return View();
            //        }
            //    }
            //    else
            //    {
            //        return Content("似乎遇到一个错误代码：" + rError.errcode + "    错误信息：" + rError.errmsg + "  请扫描下方二维码关注后重新打开");
            //    }
            //    #endregion
            //}
            #endregion
            //【2】获取参数： 
            string url = HttpContext.Request.Url.Query;
            //【1】获取完整url （协议名+域名+虚拟目录名+文件名+参数） 
            //string url1 = Request.Url.ToString();

            string canshu = url.Substring(url.LastIndexOf("=") + 1);
            string[] cs = canshu.Split('&');
            bool result = UserLoginByYzm(cs[0]);
            if (result)
            {
                Response.Redirect("Home/Index");
                return View();
            }
            else
            {
                Response.Redirect("Home/Unusual");//异常Unusual
                return View();
            }
            #region test
            //Response.Redirect("Home/Index");
            //return View();
            #endregion
        }
        #endregion

        #region 获取商户分类
        /// <summary>
        /// 获取商户分类
        /// </summary>
        /// <returns></returns>
        public ActionResult getDict()
        {
            try
            {
                string result = ZHHQ1.GetBasicDict(34, GetYZM._YZM, 1);//调用接口
                Model.DataResult dr = ParseClass<Model.DataResult>.StrDeserialize(result, 1);
                Model.Basic_Dict_T abc = new Basic_Dict_T();
                abc.DictBZ = "1";
                abc.DictId = 1;
                abc.DictKey = "1";
                abc.DictName = "全部";
                abc.DictState = 1;
                abc.DictYL = "1";
                abc.ID = 1;


                List<Model.Basic_Dict_T> ls = new List<Model.Basic_Dict_T>();//声明实体
                List<Model.Basic_Dict_T> ls1 = new List<Model.Basic_Dict_T>();//声明实体
                ls.Add(abc);
                JObject jb = JObject.Parse(result);//将返回结果进行优化

                IList<JToken> jieguo = jb["rows"].Children().ToList();


                ls1 = ParseClass<Model.Basic_Dict_T>.JsonList(jieguo);
                ls.AddRange(ls1);




                var json = new
                {
                    total = ls.Count,
                    rows = ls
                };

                return Json(ls, JsonRequestBehavior.AllowGet);
            }
            catch (Exception) { return null; }
        }
        #endregion

        #region 获取所有商户列表
        /// <summary>
        /// 获取所有商户列表
        /// </summary>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页显示的行数</param>
        /// <param name="KeyWord">搜索关键字</param>
        /// <param name="FenLei">分类</param>
        /// <param name="PaiXu">排序</param>
        /// <param name="DelMaxMon">起送价</param>
        /// <param name="DelFormMon">配送费</param>
        /// <returns></returns>
        public ActionResult getAllShopInfo(int pageIndex, int pageSize, string KeyWord, string FenLei, int PaiXu, int DelMaxMon, int DelFormMon)
        {
            try
            {
                string siteUrl = ConfigurationManager.AppSettings["Photo"];
                //KeyWord = "1";
                if (FenLei == "0" || FenLei == "1")
                {
                    FenLei = "";

                }
                string result = DCXT2.GetShopList(pageIndex, pageSize, KeyWord, FenLei, PaiXu, DelMaxMon, DelFormMon, GetYZM._YZM, 1);
                Model.View_Order_MerSet vom = ParseClass<Model.View_Order_MerSet>.StrDeserialize(result, 1);

                List<Model.View_Order_MerSet> voms = new List<Model.View_Order_MerSet>();
                JObject jb = JObject.Parse(result);

                IList<JToken> jieguoa = jb["rows"].Children().ToList();

                voms = ParseClass<Model.View_Order_MerSet>.JsonList(jieguoa);
                //拼接图片地址
                for (int i = 0; i < voms.Count; i++)
                {
                    //voms[i].MerPic = siteUrl + voms[i].MerPic;
                    voms[i].MerPic = voms[i].MerPic;
                }

                var json = new
                {
                    total = jb["total"].ToString(),
                    rows = voms
                };

                return Json(json, JsonRequestBehavior.AllowGet);
            }
            catch (Exception) { return null; }

        }
        #endregion

        #region 绑定帐号
        /// <summary>
        /// 绑定帐号
        /// </summary>
        /// <param name="Acc"></param>
        /// <param name="Pwd"></param>
        /// <returns></returns>
        public ActionResult BindingLogin(string Acc, string Pwd)
        {
            try
            {
                string openid = Session[SessionStorage.OpenID].ToString();
                string result = ZHHQ1.UserWeiXinReg(Acc, Pwd, openid, GetYZM._YZM, 1);
                Log.Debug("BindingLogin", result);
                JObject job = JObject.Parse(result);
                string bs = job["BS"].ToString();
                if (bs == "1")
                {
                    return Content(bs);
                }
                else
                {
                    return Content(job["Msg"].ToString());
                }
            }
            catch (Exception ex) { return Content(ex.ToString()); }
        }
        #endregion

        #region 根据九宫格验证码获取用户信息
        public bool UserLoginByYzm(string YZM)
        {
            #region 测试用
            //YZM = "daf99424-25de-4938-93e3-14efd39ccee0";          
            #endregion 
            try
            {
                if (YZM == "")
                {
                    return false;
                }
                Log.Debug("UserLoginByYzmYZM", YZM);
                string result = ZHHQ1.UserLoginByYzm(YZM, GetYZM._YZM, 1);
                JObject job = JObject.Parse(result);
                string bs = job["BS"].ToString();
                if (bs == "1")//表示该微信号已经绑定过帐号 
                {
                    Model.View_User dataresult = new View_User();
                    IList<JToken> jieguo = job["rows"].Children().ToList();//将json数据转成多条
                    dataresult = obser<Model.View_User>.DataContractJsonDeserialize(job["rows"].ToString());//将json格式转为实体类
                    //dataresult.AccMobile = "oqxe8uIWuPuy4Ujy_aKzmneaDihI";
                    Session[SessionStorage.UserLogin] = dataresult;//将实体类保存至Session
                    Session.Timeout = 60;//设置session的有效时间为60分钟
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                Log.Error("UserLoginError", ex.ToString());
                return false;
            }
        }
        #endregion

        #region 首页信息
        /// <summary>
        /// 首页搜索、排序、一二级分类条件查询数据
        /// </summary>
        /// <param name="DishesNmae"></param>
        /// <param name="PaiXu"></param>
        /// <param name="DishesTypeID1"></param>
        /// <param name="DishesTypeID2"></param>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public ActionResult GetDishesList(string DishesNmae, int PaiXu, string DishesTypeID1, string DishesTypeID2, string YZM, int RETID)
        {
            try
            {
                string result = DCXT2.GetDishesList(DishesNmae, PaiXu, DishesTypeID1, DishesTypeID2, YZM, RETID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }

        /// <summary>
        /// 轮播图显示
        /// </summary>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public ActionResult GetOrder_DishesCarousel(string YZM, int RETID)
        {
            try
            {
                string result = DCXT2.GetOrder_DishesCarousel(YZM, RETID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }

        /// <summary>
        /// 获取商品信息
        /// </summary>
        /// <param name="YZM"></param>
        /// <param name="RETID"></param>
        /// <returns></returns>
        public ActionResult GetDishesGoods(string YZM, int RETID)
        {
            try
            {
                string result = DCXT2.GetDishesGoods(YZM, RETID);
                return Content(result);
            }
            catch (Exception) { return null; }
        }

        #endregion

    }
}
